<?php

namespace App\Admin\Service\Traits;


use App\Common\Exception\ApiMessageException;
use App\Common\Model\Model;
use App\Common\Util\ImitateAop\Attributes\Transaction;
use Psr\SimpleCache\InvalidArgumentException;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

/**
 * 通用修改更新操作
 *
 * @method beforeWrite(&$data, $id = null)
 * @method beforeUpdate(&$data, $id)
 * @method afterWrite()
 * @method afterUpdate(Model $oldModel)
 */
trait UpdateServiceTrait
{
    /**
     * @param array $data
     *
     * @return Model
     * @throws ApiMessageException
     */
    #[Transaction]
    public function update(array $data):mixed
    {
        $id          = $data[$this->model->getPrimaryKey()];
        $this->model = $this->model->find($id);
        if (!$this->model) {
            throw new ApiMessageException('数据不存在，无法修改');
        }

        $oldModel    = clone $this->model;

        method_exists($this, 'beforeWrite') and $this->beforeWrite($data, $id);
        method_exists($this, 'beforeUpdate') and $this->beforeUpdate($data, $id);

        $this->model->setAttrs(array_filter($data, fn($v) => !is_null($v)));

        $result = $this->model->save();

        if ($result) {
            method_exists($this, 'afterWrite')  and $this->afterWrite();
            method_exists($this, 'afterUpdate') and $this->afterUpdate($oldModel);
        }else{
            throw new ApiMessageException('保存失败');
        }
        return $this->model;
    }
}
